package com.sname.car.common;

import com.baidu.yun.push.auth.PushKeyPair;
import com.baidu.yun.push.client.BaiduPushClient;
import com.baidu.yun.push.exception.PushClientException;
import com.baidu.yun.push.exception.PushServerException;
import com.baidu.yun.push.model.PushMsgToSingleDeviceRequest;
import com.baidu.yun.push.model.PushMsgToSingleDeviceResponse;
import com.sname.car.common.constants.Constants;
import com.sname.car.common.exception.CarException;
import com.sname.car.user.entity.UserElement;

/**
 * Created By  醉美柳舞之众星捧月
 *
 * @author songx
 * @date 2018/9/27 12:48
 */
public class BaiduPushUtil {
    /**
     * Author song  醉美柳舞之众星捧月
     * Date & Time  2018/9/27 12:48
     * Description  百度云对于单个推送 Api
     */
    public static void pushMsgToSingleDevice(UserElement userElement, String message) throws CarException {
        PushKeyPair pair = new PushKeyPair(Constants.BAIDU_YUN_PUSH_API_KEY, Constants.BAIDU_YUN_PUSH_SECRET_KEY);
        BaiduPushClient pushClient = new BaiduPushClient(pair, Constants.CHANNEL_REST_URL);
        try {
            //  设置请求参数，创建请求实例
            PushMsgToSingleDeviceRequest request = new PushMsgToSingleDeviceRequest().
                    addChannelId(userElement.getPushChannelId()).
                    //设置消息的有效时间,单位秒,默认3600*5.
                            addMsgExpires(new Integer(3600)).
                    //设置消息类型,0表示透传消息,1表示通知,默认为0.
                            addMessageType(1).
                            addMessage(message);
            //设置设备类型，deviceType => 1 for web, 2 for pc,
            // 3for android, 4 for ios, 5 for wp.
            if ("android".equals(userElement.getPlatform())) {
                request.addDeviceType(3);
            } else if ("ios".equals(userElement.getPlatform())) {
                request.addDeviceType(4);
            }
            //  执行Http请求
            PushMsgToSingleDeviceResponse response = pushClient.pushMsgToSingleDevice(request);
        } catch (PushClientException e) {
            e.printStackTrace();
            throw new CarException(e.getMessage());
        } catch (PushServerException e) {
            e.printStackTrace();
            throw new CarException(e.getErrorMsg());
        }
    }
}
